package com.shensi.appCollect.service.impl;

import com.shensi.appCollect.constantEnum.DecimalConstant;
import com.shensi.appCollect.dao.CustomerCardSettingDetailContentMapper;
import com.shensi.appCollect.dao.CustomerCardSettingDetailMapper;
import com.shensi.appCollect.dao.CustomerCardUseRecordMapper;
import com.shensi.appCollect.dao.ElectronicMembershipCardMapper;
import com.shensi.appCollect.dao.OilMapper;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.vo.RechargePrivilegeVO;
import com.shensi.appCollect.service.CustomerCardSettingDetailService;
import com.shensi.appCollect.service.ElectronicMembershipCardService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomerCardSettingDetailServiceImpl implements CustomerCardSettingDetailService {
    @Autowired
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Autowired
    private PresentAmountRecordServiceImpl presentAmountRecordService;

    @Autowired
    private EnterpriseServiceImpl enterpriseService;

    @Autowired
    private PayOrderServiceImpl payOrderService;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private ElectronicMembershipCardMapper electronicMembershipCardMapper;
    @Autowired
    private CustomerCardSettingDetailContentMapper customerCardSettingDetailContentMapper;

    @Autowired
    private CustomerCardSettingDetailMapper customerCardSettingDetailMapper;

    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    // 瑶湖站定制需求，消费返额排除一批手机号，固定写死
    private static final Set<String> EXCLUDE_PHONE_NUMBER = new HashSet<>();
    // 瑶湖油企id，固定写死
    private static final Long YAOHU_ENTERPRISE_ID = 350L;

    static {
        EXCLUDE_PHONE_NUMBER.add("15397362095");
        EXCLUDE_PHONE_NUMBER.add("17770201116");
        EXCLUDE_PHONE_NUMBER.add("15870868776");
        EXCLUDE_PHONE_NUMBER.add("13607046930");
        EXCLUDE_PHONE_NUMBER.add("17507093998");
        EXCLUDE_PHONE_NUMBER.add("13667920108");
        EXCLUDE_PHONE_NUMBER.add("13667005907");
    }


    @Override
    public CalPresentAmt calConsumePresentAmtAndCreateRecord(String orderNo,String mobilePhone,BigDecimal receivableAmt,BigDecimal amt,
                                                             Long enterpriseId, Long stationId,String payType,String cardOilsType,
                                                             String oilGun,Integer oilId,String bussinessName,String purpose) {
        if(Objects.equals(YAOHU_ENTERPRISE_ID,enterpriseId) && EXCLUDE_PHONE_NUMBER.contains(mobilePhone)){
            // 瑶湖站定制需求，消费返额时需要排除一批手机号
            // 包含排除的手机号直接返回
            CalPresentAmt cal = new CalPresentAmt();
            cal.setPresentAmt(BigDecimal.ZERO);
            return cal;
        }
        StaOilGun staOilGun = new StaOilGun();
        staOilGun.setGunName(oilGun);
        staOilGun.setStationId(stationId.intValue());
        StaOilGun staOilGunInfo = enterpriseService.selectStaGunInfo(staOilGun);
        BigDecimal oilStationPrice = staOilGunInfo.getOilStationPrice();
        String oilPrice = oilStationPrice.toString();                    //油站油品价格
        BigDecimal oilLiters =BigDecimal.ZERO;
        if(oilId!=null){
            //Oil oil = oilMapper.selectOilById(Long.valueOf(oilId));
            //cardOilsType=oil.getCardType();
            oilLiters = receivableAmt.divide(new BigDecimal(oilPrice), 4, BigDecimal.ROUND_HALF_UP);
        }

        CalPresentAmt calPresentAmt=new CalPresentAmt();
        BigDecimal presentAmt = BigDecimal.ZERO;
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();
        //form.setParentId(cardSetting.getId());
        //form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);
        form.setDelFlag("0");
        form.setCardType(cardOilsType);
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_CONSUME);
        form.setEnterpriseId(enterpriseId);
        form.setStationId(stationId);
        form.setStatus("NORMAL");
        form.setPayType(payType);
        form.setNowDate(new Date());
        form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
        form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));
        form.setGiftType(1);


        List<CustomerCardSettingDetail> customerCardSettingDetails = electronicMembershipCardService.selectCardSettingDetail(form);

        //循环优惠规则明细
        for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {

            // 判断活动是否开启充值门槛
            if (cardDetail.getOpenTopUpThreshold() == 1){
                // 获取最后一次充值记录 判断是否满足充值门槛  获取充值记录需判断油品
                CustomerCardUseRecord customerCardUseRecord = customerCardUseRecordMapper.getCustomerCardUseRecordByPhoneStationIdOilType(
                        CustomerCardUseRecord.builder()
                                .mobilePhone(mobilePhone)
                                .stationId(Integer.valueOf(stationId.toString()))
                                .cardOilsType(cardOilsType)
                                .startTime(cardDetail.getActivityTimeStart())
                                .endTime(cardDetail.getActivityTimeEnd())
                                .build());
                if (customerCardUseRecord == null || customerCardUseRecord.getAmt().compareTo(cardDetail.getTopUpThreshold()) < 0){
                    continue;
                }
            }

            //判断是否在生效时间内
            if(!checkEffectiveTime(cardDetail)) {
                continue;
            }
            CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
            contentQuery.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
            List<CustomerCardSettingDetailContent> contentList=electronicMembershipCardService.getCardSettingDetailContents(contentQuery);
            boolean isBreak=false;
            for (CustomerCardSettingDetailContent content : contentList) {

                if(cardDetail.getAccordingTo().equals(CustomerCardSettingDetail.according_to_money)){
                    if (amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0) {
                        //充值优惠类型
                        calPresentAmt.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
                        if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                            presentAmt = content.getPresentAmount(); //当前赠送金额
                        } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                            presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                        isBreak=true;
                        break;
                    }
                }else if(cardDetail.getAccordingTo().equals(CustomerCardSettingDetail.according_to_litres)){
                    if (oilLiters.compareTo(content.getRechargeAmtLowerLimit()) >=0 && oilLiters.compareTo(content.getRechargeAmtUpperLimit())<0) {
                        calPresentAmt.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
                        if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                            presentAmt = content.getPresentAmount().multiply(oilLiters).setScale(2, BigDecimal.ROUND_HALF_UP); //当前赠送金额
                        } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                            presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                        isBreak=true;
                        break;
                    }
                }
            }
            if(isBreak){
                break;
            }
        }

        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId.intValue());


        CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                .cardOilsType(cardOilsType)
                .mobilePhone(mobilePhone);
        if (StringUtils.equals("1",enterprise.getCardUseRangeFlag())) {
            builder.stationId(enterpriseId.intValue());
        }else{
            builder.stationId2(stationId.intValue());
        }
        CustomerElectronicCard electronicCardInfoByPhone = electronicMembershipCardMapper.getElectronicCardInfoByPhone(builder.build());
        if(electronicCardInfoByPhone!=null){
            BigDecimal cardPresentAmt = electronicCardInfoByPhone.getPresentAmt();
            if(cardPresentAmt==null){
                cardPresentAmt=BigDecimal.ZERO;
            }
            cardPresentAmt=cardPresentAmt.add(presentAmt);
            electronicCardInfoByPhone.setPresentAmt(cardPresentAmt);
            //更新电子卡赠送金额
            electronicMembershipCardMapper.updateElectronicCardInfo(electronicCardInfoByPhone);
            calPresentAmt.setPresentAmt(presentAmt);
            //赠送金额记录
            if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                createRecord(presentAmt,bussinessName,mobilePhone,orderNo,purpose,electronicCardInfoByPhone.getId().longValue(),calPresentAmt.getCcsdId());
            }

        }
        return calPresentAmt;
    }

    @Override
    public CalPresentAmt calConsumePresentAmtAndCreateRecordReturnCash(String orderNo, String mobilePhone, BigDecimal receivableAmt,
                                                                       BigDecimal amt, Long enterpriseId, Long stationId, String payType,
                                                                       String cardOilsType, String gunName, Integer oilId, String bussinessName,
                                                                       String purpose,boolean genericPay,String cardType) {
        if(Objects.equals(YAOHU_ENTERPRISE_ID,enterpriseId) && EXCLUDE_PHONE_NUMBER.contains(mobilePhone)){
            // 瑶湖站定制需求，消费返额时需要排除一批手机号
            // 包含排除的手机号直接返回
            CalPresentAmt cal = new CalPresentAmt();
            cal.setPresentAmt(BigDecimal.ZERO);
            return cal;
        }
        StaOilGun staOilGun = new StaOilGun();
        staOilGun.setGunName(gunName);
        staOilGun.setStationId(stationId.intValue());
        StaOilGun staOilGunInfo = enterpriseService.selectStaGunInfo(staOilGun);
        BigDecimal oilStationPrice = staOilGunInfo.getOilStationPrice();
        String oilPrice = oilStationPrice.toString();                    //油站油品价格
        BigDecimal oilLiters =BigDecimal.ZERO;
        if(oilId!=null){
            //Oil oil = oilMapper.selectOilById(Long.valueOf(oilId));
            //cardOilsType=oil.getCardType();
            oilLiters = receivableAmt.divide(new BigDecimal(oilPrice), 4, BigDecimal.ROUND_HALF_UP);
        }

        CalPresentAmt calPresentAmt=new CalPresentAmt();
        BigDecimal presentAmt = BigDecimal.ZERO;
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();
        //form.setParentId(cardSetting.getId());
        //form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);
        form.setDelFlag("0");
        form.setCardType(genericPay?"0":cardType); //获取油品或者通用卡对应的活动
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_CONSUME);
        form.setEnterpriseId(enterpriseId);
        form.setStationId(stationId);
        form.setStatus("NORMAL");
        form.setPayType(payType);
        form.setNowDate(new Date());
        form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
        form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));


        List<CustomerCardSettingDetail> customerCardSettingDetails = customerCardSettingDetailMapper.getPaySatisfyCustomerCardSettingDetail(form);

        //循环优惠规则明细
        for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {
            calPresentAmt.setGiftType(cardDetail.getGiftType());
            // 判断活动是否开启充值门槛
            if (cardDetail.getOpenTopUpThreshold().equals("1")){
                // 获取最后一次充值记录 判断是否满足赠送返利金的要求  获取充值记录需判断油品和通用卡
                CustomerCardUseRecord customerCardUseRecord = customerCardUseRecordMapper.getCustomerCardUseRecordByPhoneStationIdOilType(
                        CustomerCardUseRecord.builder()
                                .mobilePhone(mobilePhone)
                                .stationId(Integer.valueOf(stationId.toString()))
                                .cardOilsType(genericPay ? "0" : cardOilsType)
                                .startTime(cardDetail.getActivityTimeStart())
                                .endTime(cardDetail.getActivityTimeEnd())
                                .build());
                if (customerCardUseRecord == null || customerCardUseRecord.getAmt().compareTo(cardDetail.getTopUpThreshold()) < 0){
                    continue;
                }
            }

            //判断是否在生效时间内
            if(!checkEffectiveTime(cardDetail)) {
                continue;
            }

            CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
            contentQuery.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
            List<CustomerCardSettingDetailContent> contentList=electronicMembershipCardService.getCardSettingDetailContents(contentQuery);
            boolean isBreak=false;
            for (CustomerCardSettingDetailContent content : contentList) {

                if(cardDetail.getAccordingTo().equals(CustomerCardSettingDetail.according_to_money)){
                    if (amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0) {
                        //充值优惠类型
                        calPresentAmt.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
                        if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                            presentAmt = content.getPresentAmount(); //当前赠送金额
                        } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                            presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                        isBreak=true;
                        break;
                    }
                }else if(cardDetail.getAccordingTo().equals(CustomerCardSettingDetail.according_to_litres)){
                    if (oilLiters.compareTo(content.getRechargeAmtLowerLimit()) >=0 && oilLiters.compareTo(content.getRechargeAmtUpperLimit())<0) {
                        calPresentAmt.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
                        if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                            presentAmt = content.getPresentAmount(); //当前赠送金额
                        } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                            presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                        isBreak=true;
                        break;
                    }
                }
            }
            if(isBreak){
                break;
            }
        }

        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId.intValue());

        CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                .mobilePhone(mobilePhone);
        if (StringUtils.equals("1",enterprise.getCardUseRangeFlag())) {
            builder.stationId(enterpriseId.intValue());
        }else{
            builder.stationId2(stationId.intValue());
        }

        if (calPresentAmt.getGiftType()!=null && calPresentAmt.getGiftType() == 1){
            builder.cardOilsType(genericPay?"0":cardOilsType);
            CustomerElectronicCard electronicCardInfoByPhone = electronicMembershipCardMapper.getElectronicCardInfoByPhone(builder.build());
            if(electronicCardInfoByPhone!=null){
                BigDecimal presentAmt1 = electronicCardInfoByPhone.getPresentAmt();
                if(presentAmt1==null){
                    presentAmt1=BigDecimal.ZERO;
                }
                presentAmt1 = presentAmt1.add(presentAmt);
                electronicCardInfoByPhone.setPresentAmt(presentAmt1);
                //更新电子卡返利金额
                electronicMembershipCardMapper.updateElectronicCardInfo(electronicCardInfoByPhone);
                calPresentAmt.setPresentAmt(presentAmt);
                //赠送金额记录
                if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                    createRecord(presentAmt,bussinessName,mobilePhone,orderNo,purpose,electronicCardInfoByPhone.getId().longValue(),calPresentAmt.getCcsdId());
                }
            }
        } else if (calPresentAmt.getGiftType()!=null && calPresentAmt.getGiftType() == 2){
            // 赠送返利金要获取指定返利金账户
            CustomerElectronicCard electronicCardInfoByPhone = electronicMembershipCardMapper.getElectronicCardInfoByReturnCash(builder.build());
            if(electronicCardInfoByPhone!=null){
                BigDecimal returnCashAmt = electronicCardInfoByPhone.getReturnCashAmt();
                if(returnCashAmt==null){
                    returnCashAmt=BigDecimal.ZERO;
                }
                returnCashAmt = returnCashAmt.add(presentAmt);
                electronicCardInfoByPhone.setReturnCashAmt(returnCashAmt);
                //更新电子卡返利金额
                electronicMembershipCardMapper.updateElectronicCardInfo(electronicCardInfoByPhone);
                calPresentAmt.setPresentAmt(presentAmt); // 设置返利金
            }
        }
        return calPresentAmt;
    }

    @Override
    public boolean checkEffectiveTime(CustomerCardSettingDetail cardDetail) {
        try{
            Date nowDate = new Date();
            String periodType = cardDetail.getPeriodType();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyy-MM-dd");
            SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            String ymd = simpleDateFormat.format(nowDate);
            boolean condition1=false;
            boolean condition2=false;
            if(periodType.contains(CustomerCardSettingDetail.periodType_week)){
                Integer week=Integer.parseInt(CustomerCardSettingDetail.dateToWeek(nowDate));
                String weeklySelection = cardDetail.getWeeklySelection();
                List<Integer> weekList = Arrays.stream(weeklySelection.split(",")).map(s -> Integer.parseInt(s)).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                if(weekList.contains(week)){
                    condition1=true;

                    if(cardDetail.getWeekTimeRangeType().equals(CustomerCardSettingDetail.TIMERANGETYPE_ENTIRE)){
                        Integer startWeek = weekList.get(0);
                        Integer endWeek = weekList.get(weekList.size() - 1);
                        String ymdhms="";
                        if(startWeek.equals(week)){
                            ymdhms=ymd+" "+cardDetail.getWeekEffectiveTimeStart().toString();
                            Date parse = simpleDateFormat2.parse(ymdhms);
                            if(nowDate.getTime()<parse.getTime()){
                                condition1=false;
                            }else{
                                condition1=true;
                            }
                        }
                        if(endWeek.equals(week)){
                            ymdhms=ymd+" "+cardDetail.getWeekEffectiveTimeEnd().toString();
                            Date parse = simpleDateFormat2.parse(ymdhms);
                            if(nowDate.getTime()>parse.getTime()){
                                condition1=condition1&&false;
                            }else{
                                condition1=condition1&&true;
                            }
                        }
                        if(startWeek.equals(endWeek)){
                            Date weekEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeStart().toString());
                            Date weekEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeEnd().toString());
                            if(nowDate.getTime()<=weekEffectiveTimeEnd.getTime()&&nowDate.getTime()>=weekEffectiveTimeStart.getTime()){
                                condition1=true;
                            }else{
                                condition1=false;
                            }

                        }
                    }else{
                        Date weekEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeStart().toString());
                        Date weekEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeEnd().toString());
                        if(nowDate.getTime()<=weekEffectiveTimeEnd.getTime()&&nowDate.getTime()>=weekEffectiveTimeStart.getTime()){
                            condition1=true;
                        }else{
                            condition1=false;
                        }
                    }
                }else{
                    condition1= false;
                }


            }
            if(periodType.contains(CustomerCardSettingDetail.periodType_month)){
                Integer month=Integer.parseInt(CustomerCardSettingDetail.dateToMonth(nowDate));
                String monthlySelection = cardDetail.getMonthlySelection();
                List<Integer> monthList = Arrays.stream(monthlySelection.split(",")).map(s -> Integer.parseInt(s)).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                if(monthList.contains(month)){
                    condition2=true;

                    if(cardDetail.getMonthTimeRangeType().equals(CustomerCardSettingDetail.TIMERANGETYPE_ENTIRE)){
                        Integer startMonth = monthList.get(0);
                        Integer endMonth = monthList.get(monthList.size() - 1);
                        String ymdhms="";
                        if(startMonth.equals(month)){
                            ymdhms = ymd+" "+cardDetail.getMonthEffectiveTimeStart().toString();
                            Date parse = simpleDateFormat2.parse(ymdhms);
                            if(nowDate.getTime()<parse.getTime()){
                                condition2=false;
                            }else{
                                condition2=true;
                            }
                        }
                        if(endMonth.equals(month)){
                            ymdhms = ymd+" "+cardDetail.getMonthEffectiveTimeEnd().toString();
                            Date parse = simpleDateFormat2.parse(ymdhms);
                            if(nowDate.getTime()>parse.getTime()){
                                condition2=condition2&&false;
                            }else{
                                condition2=condition2&&true;
                            }
                        }
                        if(endMonth.equals(startMonth)){
                            Date monthEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeStart().toString());
                            Date monthEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeEnd().toString());
                            if(nowDate.getTime()<=monthEffectiveTimeEnd.getTime()&&nowDate.getTime()>=monthEffectiveTimeStart.getTime()){
                                condition2=true;
                            }else{
                                condition2=false;
                            }
                        }
                    }else{
                        Date monthEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeStart().toString());
                        Date monthEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeEnd().toString());
                        if(nowDate.getTime()<=monthEffectiveTimeEnd.getTime()&&nowDate.getTime()>=monthEffectiveTimeStart.getTime()){
                            condition2=true;
                        }else{
                            condition2=false;
                        }
                    }
                }else{
                    condition2= false;
                }


            }
            if(periodType.contains("all")){
                return true;
            }
            return condition1||condition2;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public PresentAmountRecord createRecord(BigDecimal presentAmt, String bussinessName, String mobilePhone, String orderNo, String purpose, Long cecId, Long ccsdId) {
        PresentAmountRecord presentAmountRecord=new PresentAmountRecord();
        presentAmountRecord.setPresentAmount(presentAmt);
        presentAmountRecord.setBusinessName(bussinessName);
        presentAmountRecord.setMobilePhone(mobilePhone);
        presentAmountRecord.setOrderNo(orderNo);
        presentAmountRecord.setPurpose(purpose);
        presentAmountRecord.setCecId(cecId);
        presentAmountRecord.setCcsdId(ccsdId);
        return presentAmountRecordService.insert(presentAmountRecord);

    }

    @Override
    public List<RechargePrivilegeVO> getStationRechargePrivilegeList(Long stationId, String cardType) {
        LocalDate nowDate = LocalDate.now();
        int week = nowDate.getDayOfWeek().getValue();
        int month = nowDate.getDayOfMonth();
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();
        form.setDelFlag("0");
        form.setCardType(cardType);
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
        //form.setEnterpriseId(enterpriseId);
        form.setStationId(stationId);
        form.setStatus("NORMAL");
        form.setPayType("wx");
        form.setNowDate(new Date());
        form.setWeeklySelection(String.valueOf(week));
        form.setMonthlySelection(String.valueOf(month));
        List<CustomerCardSettingDetail> customerCardSettingDetails = electronicMembershipCardService.selectCardSettingDetail(form);
        Map<Integer,CustomerCardSettingDetail> idMap = new HashMap<>();
        List<Integer> ccsdIds = new ArrayList<>();
        for (CustomerCardSettingDetail settingDetail : customerCardSettingDetails) {
            if (!checkEffectiveTime(settingDetail)) {
                continue;
            }
            idMap.put(settingDetail.getCardSettingDetailId(), settingDetail);
            ccsdIds.add(settingDetail.getCardSettingDetailId());
        }
        if (ccsdIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<CustomerCardSettingDetailContent> contents = customerCardSettingDetailContentMapper.queryListByCcsdIds(ccsdIds);
        ArrayList<BigDecimal> amtList = new ArrayList<>(contents.size()*2);
        for (CustomerCardSettingDetailContent content : contents) {
            amtList.add(content.getRechargeAmtLowerLimit());
            amtList.add(content.getRechargeAmtUpperLimit());
        }
        amtList.sort(BigDecimal::compareTo);
        ArrayList<RechargePrivilegeVO> privilegeVOS = new ArrayList<>(contents.size());
        int size = amtList.size();
        int li = size - 1;
        for (int i = 0; i < size; i++) {
            BigDecimal amt = amtList.get(i);
            if (i<li) {
                BigDecimal next = amtList.get(i + 1);
                if (amt.compareTo(next)==0) {
                    continue;
                }
            }
            List<CustomerCardSettingDetailContent> contantList = contents.stream().filter(c -> amt.compareTo(c.getRechargeAmtLowerLimit()) >= 0 && amt.compareTo(c.getRechargeAmtUpperLimit()) < 0).collect(Collectors.toList());
            if (contantList.isEmpty()) {
                continue;
            }
            RechargePrivilegeVO privilegeVO = new RechargePrivilegeVO();
            privilegeVO.setMinRechargeAmt(amt);
            for (CustomerCardSettingDetailContent content : contantList) {
                CustomerCardSettingDetail settingDetail = idMap.get(Math.toIntExact(content.getCcsdId()));
                if (settingDetail != null) {
                    String activityType = settingDetail.getActivityType();
                    if (StringUtils.equals(CustomerCardSettingDetail.ACTIVITYTYPE_COUPON, activityType)) {
                        privilegeVO.setHasCoupons(Boolean.TRUE);
                    }else if(StringUtils.equals(CustomerCardSettingDetail.ACTIVITYTYPE_INTEGRAL, activityType)){
                        privilegeVO.setPresentIntegral(amt.multiply(content.getPresentAmount()).intValue());
                    }else if(StringUtils.equals(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE, activityType)){
                        if (StringUtils.equals("1",settingDetail.getSettingRuleType())) { //按充值金额
                            privilegeVO.setPresentAmt(content.getPresentAmount());
                        } else if (StringUtils.equals("2", settingDetail.getSettingRuleType())) {      //按充值金额的比例
                            privilegeVO.setPresentAmt(amt.multiply(content.getPresentAmount()).multiply(DecimalConstant.O_01).setScale(2,RoundingMode.DOWN));
                        }
                    }
                }
            }
            if((privilegeVO.getPresentIntegral() != null && privilegeVO.getPresentIntegral() > 0)
                    || (privilegeVO.getHasCoupons() != null && privilegeVO.getHasCoupons())
                    || (privilegeVO.getPresentAmt() != null && privilegeVO.getPresentAmt().compareTo(BigDecimal.ZERO)>0)){
                privilegeVOS.add(privilegeVO);
            }
        }
        return privilegeVOS;
    }

    private Boolean timeInScope(LocalTime comparedTime ,LocalTime startTime, LocalTime endTime){
//        LocalTime nowTime = LocalTime.of(5,54,07);
        if(startTime == null || endTime == null){
            return true;  // 有一个为null 直接放行
        }else if(startTime.isBefore(endTime) && startTime.isBefore(comparedTime) && endTime.isAfter(comparedTime) ){
            return true;
            //  大 小
        }else if(startTime.isAfter(endTime) ){
            //小 大
            if(startTime.isBefore(comparedTime)){
                return true;
            }
            //大 小
            if(endTime.isAfter(comparedTime)){
                return true;
            }
        }else if(startTime.equals(comparedTime)){
            return true;
        }else if(endTime.equals(comparedTime)){
            return true;
        }
        return false;
    }
}
